package cn.bd13.xinapp.service.web.impl;


import cn.bd13.xinapp.dao.web.AdminDao;
import cn.bd13.xinapp.model.dto.AddForm;
import cn.bd13.xinapp.model.dto.AdminVo;
import cn.bd13.xinapp.model.dto.MenuVo;
import cn.bd13.xinapp.model.entity.Admin;
import cn.bd13.xinapp.model.entity.Menu;
import cn.bd13.xinapp.service.web.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminDao adminDao;


    @Override
    public Admin getAdminByPhone(String phone) {
        return adminDao.getAdminByPhone(phone);
    }

    @Override
    public List<MenuVo> getMenusByAtype(int atype) throws Exception{

        //首先获取这个权限对应的一级目录
        List<MenuVo> menuVoList=adminDao.getFirstLevelMenus(atype);

        //循环，通过这个权限，以及当前一级目录的id，获取对应的二级目录
        for (MenuVo vo:menuVoList){
            List<Menu> menus=adminDao.getSecondLevelMenus(atype,vo.getMenuid());
            //并将二级目录的集合，存入以及目录对象的children属性中
            vo.setChildren(menus);
        }
        return menuVoList;
    }

    @Override
    public List<AdminVo> queryAdminCtds(String query, int pagenum, int pagesize) throws Exception {
        //查询截取的起始位置
        int index=(pagenum-1)*pagesize;
        //这是从数据库中查到的数据
        List<Admin> adminList = adminDao.queryAdmin(query,pagesize,index);

        //准备一个返回数据，是针对前端使用的
        List<AdminVo> adminVoList=new ArrayList<>();

        for (Admin admin:adminList){
            AdminVo adminVo=new AdminVo();
            BeanUtils.copyProperties(admin,adminVo);
            //给statusBoolean属性赋值
            if (admin.getStatus()==1){
                adminVo.setStatusBoolean(true);
            }else{
                adminVo.setStatusBoolean(false);
            }
            //给时间赋值
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            adminVo.setCreatedTimeStr(format.format(admin.getCreatedTime()));
            adminVo.setUpdatedTimeStr(format.format(admin.getUpdatedTime()));
            adminVoList.add(adminVo);
        }
        return adminVoList;
    }

    @Override
    public int queryAdminCtdsCount(String query) throws Exception {
        return adminDao.queryAdminCount(query);
    }

    @Override
    public void updAdminStatus(int aid) throws Exception {
        Admin admin=adminDao.getAdminById(aid);
        int status=0;
        if (admin.getStatus()==0){
            status=1;
        }
        adminDao.updAdminStatus(aid,status);
    }

    @Override
    public void addAdmin(AddForm form) throws Exception {
        adminDao.addAdmin(form);
    }
}
